<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>图片管理器</title>
    <meta name="author" content="yinqi">
    <link href="../dialog/css/bootstrap.min.css" rel="stylesheet">
    <link href="../dialog/css/materialdesignicons.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../dialog/css/style.min.css">
    <link rel="stylesheet" type="text/css" href="../dialog/js/layer/css/layui.css">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <style>
        body{
            background: #eee;
        }


        /* 默认的搜索框 */
        .lyear-search {
            position: relative;
            z-index: 0;
            display: -webkit-inline-box;
            display: inline-flex;
        }
        .lyear-search input {
            width: 300px;
            padding-left: 10px;
            -webkit-transition: .5s;
            transition: .5s;
        }
        .lyear-search.lyear-search-right input {
            padding-left: 12px;
            padding-right: 35px;
        }
        .layui-laypage-count{
            background: none!important;
        }
        .layui-laypage .layui-laypage-curr .layui-laypage-em{
            background: #33cabb!important;
        }
        .layui-flow-more{
            display: block;
            min-width: 100px;
            width: 20%!important;
            text-align: center;
            position: absolute!important;
            bottom: 0px;
            left: 40%;
        }
        .masonry-item img{
            width: 100%;
            border: 1px dashed transparent;
        }
        .masonry-item img:hover{
            border: 1px dashed #f33;
            opacity: 0.5;
        }
        .item-this{
            border: 1px dashed #f33!important;
            opacity: 0.5;
        }
        .masonry-item .image-text {
            text-align: center;
            width: 100%;
            display: block;
            background: #fff!important;
            line-height: 2em;
            color: #465161;;
        }
    </style>
</head>

<body>
<div>

    <div class="row">
        <div class="col-md-12">
            <div class="card  card-image">
                <div class="card-body">
                    <div class="form-group" style="float: left;margin-bottom: 0rem;">
                        <div class="btn-group">
                            <button class="btn btn-default" id="image-upload"><i class="layui-icon layui-icon-upload-drag"></i>上传</button>
                            <button class="btn btn-default" id="image-delete"><i class="layui-icon layui-icon-delete"></i>删除</button>
                        </div>
                    </div>
                    <div class="form-group" style="float: right;">
                        <form class="lyear-search lyear-search-left">
                            <div class="input-group">
                                <input onkeydown="if(window.event.keyCode==13){return false;}" type="text" id="image-keyword" name="keyword" class="form-control" placeholder="请输入搜索的关键词...">
                                <div class="input-group-btn">
                                    <button type="button" class="btn btn-default" id="keyword-search">搜索</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>


    <!--第二种布局方式-->
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body">

                    <div class="masonry-grid" data-provide="photoswipe" id="imageList">

                    </div>

                </div>
            </div>
        </div>

    </div>




</div>

<div style="text-align: center; background-color:#FFF; position: fixed; bottom: 0px; width: 100%;opacity: 0.8; padding-top: 8px; padding-bottom: 8px;"  id="confirmSelect">
    <button type="button" class="btn btn-primary" id="okSelect">确 认</button>
    <button type="button" class="btn btn-default" onclick="javascript:parent.layer.closeAll();">关 闭</button>

</div>

<script type="text/javascript" src="../js/layer/layui.js"></script>
<script>
    var imageMenuId = 'Sysimage';
    ready(function() {
        layui.use(['flow', 'zhanshop'], function(){
            var $ = layui.jquery; //不用额外加载jQuery，flow模块本身是有依赖jQuery的，直接用即可。
            var flow = layui.flow;
            flow.load({
                elem: '#imageList' //指定列表容器
                ,isAuto: true
                ,isLazyimg: false
                ,done: function(page, next){ //到达临界点（默认滚动触发），触发下一页
                    var lis = [];
                    //以jQuery的Ajax请求为例，请求下一页数据（注意：page是从2开始返回）
                    var reqData = {
                        '_method' : 'GET',
                        'page' : page,
                        'limit' : 20,
                        'search' : [['original', 'like', layui.zhanshop.getParam('keyword')]]
                    };
                    layui.zhanshop.ajax(API_ADDRESS+apiUrlTable+"/"+imageMenuId, 'POST', reqData, {}, function(res){
                        //假设你的列表返回在data集合中
                        layui.each(res.data.list, function(index, item){
                            lis.push('<a class="masonry-item" href="javascript:void(0)"><img  data-data=\''+JSON.stringify(item)+'\' class="item-image" src="'+item.url+'" alt="'+item.original+'"><i class="image-text">'+item.original+'</i></a>');
                        });

                        //执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
                        //pages为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
                        next(lis.join(''), page < Math.ceil(res.data.total/ 20));

                        if(layui.zhanshop.getParam('multi')){
                            var inputVal = $('#'+parent.layui.zhanshopFrom.currentInputId, window.parent.document).val();
                            var vals = inputVal ? JSON.parse(inputVal) : [];
                            $('.item-image').each(function(){
                                if(vals.indexOf(this.src) >= 0){
                                    $(this).addClass('item-this');
                                    $(this).addClass('input-select');
                                }
                            });
                        }

                    }, function(xhr){}, true);
                }
            });

            $(document).on('click', '.item-image', function() {
                if(layui.zhanshop.getParam('multi') == ''){
                    $('.item-image').each(function(){
                        $(this).removeClass('item-this');
                    });
                }
                if($(this).hasClass("item-this")){

                    if(layui.zhanshop.getParam('multi') && $(this).hasClass("input-select")){
                        var domId = parent.layui.zhanshopFrom.currentInputId;
                        var inputVal = $('#'+domId, window.parent.document).val();
                        inputVal = JSON.parse(inputVal);
                        var thisSrc = this.src;
                        var valKey = inputVal.indexOf(thisSrc);
                        console.log(valKey);
                        if(valKey >= 0){
                            inputVal.splice(valKey,1); // 删除元素
                        }
                        $('#'+domId, window.parent.document).val(JSON.stringify(inputVal));

                        // 删除图片
                        $('#'+domId, window.parent.document).parent().find('img').each(function(){
                            if(this.src == thisSrc) $(this).parent().parent().remove();
                        });

                    }

                    $(this).removeClass('item-this');
                }else{
                    if(layui.zhanshop.getParam('multi') == false){
                        // 删除其他所有
                        $('.item-this').each(function(){
                            $(this).removeClass('item-this');
                        });
                    }
                    $(this).addClass('item-this');
                }
            });

            $(document).on('click', '#image-upload', function() {
                window.location = './dialog/upload-image.html?t='+(new Date().getTime());
            });
            $('#image-keyword').val(layui.zhanshop.getParam('keyword'));
            $(document).on('click', '#keyword-search', function() {
                // 触发搜索
                var keyword = $('#image-keyword').val();
                var searchUrl = window.location.href;
                searchUrl = searchUrl.split('?');
                if(keyword == ''){
                    window.location = searchUrl[0]+'?_id='+imageMenuId;
                    return false;
                }
                window.location = searchUrl[0]+'?_id='+imageMenuId+'&keyword='+keyword;
                return false;
            });

            $(document).on('click', '#image-delete', function() {
                var reqData = {
                    "_method": "DELETE",
                    "pk": []
                };
                $('.item-this').each(function(index){
                    var data = $(this).data('data');
                    reqData["pk"].push(data.image_id)
                });
                if(reqData["pk"].length <= 0){
                    return layui.zhanshop.alert('请先选中需要删除的图片', 'danger');
                }
                layui.zhanshop.confirm('确定要删除么?', function(){
                    layui.zhanshop.ajax(API_ADDRESS+apiUrlTable+'/'+imageMenuId, 'POST', reqData, {}, function(data){
                        // 删除指定元素即可
                        $('.item-this').each(function(){
                            $(this).parent().remove(); // 删除自身
                        });
                    },function(xhr){return layui.zhanshop.alert(xhr.responseJSON[apiMsg] ? xhr.responseJSON[apiMsg] : xhr.statusText, 'danger');}, true, true);
                }, function(){

                });
            });

            $(document).on('click', '#okSelect', function() {
                if(layui.zhanshop.getParam('multi')){
                    checkSelect();
                }else{
                    radioSelect();
                }
            });

            function radioSelect(){
                // 单选就是替换 多选就是追加,还有已选的选择呢
                var domId = parent.layui.zhanshopFrom.currentInputId;
                var urls = [];
                var imgsHtml = '';
                $('.item-this').each(function(index){
                    urls.push(this.src);
                    imgsHtml += '<li class="col-6 col-md-4 col-lg-2"><figure><img src="'+this.src+'" min-height="200px"><figcaption><a class="btn btn-round btn-square btn-danger inputImageDel" href="javascript:void(0)"><i class="mdi mdi-close image-delete"></i></a></figcaption></figure></li>';
                });
                // 把图片处理一下
                $('#'+domId, window.parent.document).parent().find('ul').html(imgsHtml);

                if(urls.length == 1) urls = urls[0];
                $('#'+domId, window.parent.document).val(urls);
                parent.layer.closeAll();
            }

            function checkSelect(){
                var maxLength = 12;
                // 单选就是替换 多选就是追加,还有已选的选择呢
                var domId = parent.layui.zhanshopFrom.currentInputId;
                var vals = $('#'+domId, window.parent.document).val(); // 合并两边的值
                var vals = vals ? JSON.parse(vals) : [];
                imgsHtml = '';
                for(var i in vals){
                    imgsHtml += '<li class="col-6 col-md-4 col-lg-2"><figure><img src="'+vals[i]+'" min-height="200px"><figcaption><a class="btn btn-round btn-square btn-danger inputImagesDel" href="javascript:void(0)"><i class="mdi mdi-close image-delete"></i></a></figcaption></figure></li>';
                }
                $('.item-this').each(function(index){
                    if(vals.indexOf(this.src) < 0){
                        vals.push(this.src);
                        imgsHtml += '<li class="col-6 col-md-4 col-lg-2"><figure><img src="'+this.src+'" min-height="200px"><figcaption><a class="btn btn-round btn-square btn-danger inputImagesDel" href="javascript:void(0)"><i class="mdi mdi-close image-delete"></i></a></figcaption></figure></li>';
                    }
                });
                imgsHtml += '<li class="col-6 col-md-4 col-lg-2"><a class="add images-add" ></a></li>';
                // 把图片处理一下
                if(vals.length > maxLength) return layui.zhanshop.alert('最大不能选择'+maxLength+'个', danger);
                $('#'+domId, window.parent.document).parent().find('ul').html(imgsHtml);
                vals = JSON.stringify(vals);
                if(vals == '[]') vals = '';
                $('#'+domId, window.parent.document).val(vals);
                parent.layer.closeAll();
            }
            // 默认选中样式
        });
    })


</script>
</body>
</html>